<template>
  <view class="container">
    <!-- 顶部个人信息 -->
    <view class="header">
      <view class="avatar">
        <!-- 展示用户头像 -->
        <image v-if="avatarUrl" :src="avatarUrl" mode="aspectFill" style="width: 100%; height: 100%; border-radius: 50%;" />
        <uni-icons v-else color="#333" size="32" type="person"></uni-icons>
      </view>
      <view class="user-info">
        <text class="name">{{ nickName || '暂无姓名' }}</text>
        <text class="position">{{ deptName || '暂无职位信息' }}</text>
      </view>
    </view>

    <!-- 扫码区域 -->
    <view class="scan-area">
      <view class="scan-button" @click="handleScanClick">
        <uni-icons color="#fff" size="80" type="scan"></uni-icons>
      </view>
      <text class="scan-text">点击扫码</text>
    </view>

    <!-- 扫码选择弹窗 -->
    <view v-if="isScanPopupVisible" class="popup-mask" @click="closeScanPopup">
      <view class="popup-content scan-popup" @click.stop>
        <view class="popup-header">
          <text class="popup-title">选择输入方式</text>
          <view class="popup-close" @click="closeScanPopup">
            <uni-icons type="close" size="24" color="#666666"></uni-icons>
          </view>
        </view>
        <view class="scan-options">
          <view class="scan-option" @click="handleScan">
            <view class="scan-icon-wrapper">
              <uni-icons type="scan" size="40" color="#2979ff"></uni-icons>
            </view>
            <text class="scan-text">扫码输入</text>
          </view>
          <view class="scan-divider"></view>
          <view class="scan-option" @click="showManualInput">
            <view class="scan-icon-wrapper">
              <uni-icons type="compose" size="40" color="#2979ff"></uni-icons>
            </view>
            <text class="scan-text">手动输入</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 手动输入弹窗 -->
    <view v-if="isManualInputVisible" class="popup-mask" @click="closeManualInput">
      <view class="popup-content manual-input-popup" @click.stop>
        <view class="popup-header">
          <text class="popup-title">输入铅封编号</text>
          <view class="popup-close" @click="closeManualInput">
            <uni-icons type="close" size="24" color="#666666"></uni-icons>
          </view>
        </view>
        <view class="input-area">
          <input
            type="text"
            class="manual-input"
            v-model="currentSnCode"
            placeholder="请输入铅封编号"
            placeholder-class="input-placeholder"
          />
          <button class="confirm-button" @click="handleConfirmInput">
            <text class="button-text">确认</text>
          </button>
        </view>
      </view>
    </view>

    <!-- 选择操作弹窗 -->
    <view v-if="isPopupVisible" class="popup-mask" @click="closePopup">
      <view class="popup-content" @click.stop>
        <view class="popup-header">
          <text class="popup-title operation-title">请选择操作</text>
          <view class="popup-close" @click="closePopup">
            <uni-icons type="close" size="24" color="#666666"></uni-icons>
          </view>
        </view>
        <view class="popup-buttons">
          <uni-button type="primary" class="action-button" @click="onUnseal">
            拆封
          </uni-button>
          <uni-button type="default" class="action-button outlined" @click="onApply">
            施打
          </uni-button>
        </view>
      </view>
    </view>

    <!-- 铅封溯源弹窗 -->
    <view v-if="isTracePopupVisible" class="popup-mask" @click="closeTracePopup">
      <view class="popup-content scan-popup" @click.stop>
        <view class="popup-header">
          <text class="popup-title">选择输入方式</text>
          <view class="popup-close" @click="closeTracePopup">
            <uni-icons type="close" size="24" color="#666666"></uni-icons>
          </view>
        </view>
        <view class="scan-options">
          <view class="scan-option" @click="handleTraceScan">
            <view class="scan-icon-wrapper">
              <uni-icons type="scan" size="40" color="#2979ff"></uni-icons>
            </view>
            <text class="scan-text">扫码输入</text>
          </view>
          <view class="scan-divider"></view>
          <view class="scan-option" @click="showTraceManualInput">
            <view class="scan-icon-wrapper">
              <uni-icons type="compose" size="40" color="#2979ff"></uni-icons>
            </view>
            <text class="scan-text">手动输入</text>
          </view>
        </view>
      </view>
    </view>
    <!-- 功能区域 -->
    <view class="function-grid">
      <view v-for="(item, index) in functionList" :key="index" class="grid-item" @click="handleFunction(item.type)">
        <view class="icon-wrapper">
          <image v-if="item.image" :src="item.image" mode="aspectFit" class="icon-img"></image>
          <uni-icons v-else :type="item.icon" color="#333" size="24"></uni-icons>
          <view v-if="item.badge" class="badge" :style="{ backgroundColor: item.badgeColor }">
            {{ item.badge }}
          </view>
        </view>
        <text class="function-text">{{ item.name }}</text>
      </view>
    </view>

    <!-- 底部占位区域 -->
    <view class="bottom-placeholder"></view>

    <view
        v-if="showCustomToast"
        class="custom-toast"
        :style="{ zIndex: 999999 }"
    >
      <text class="toast-text">{{ toastMessage }}</text>
    </view>
  </view>
</template>

<script lang="ts" setup>
import {onMounted,ref} from 'vue';
import {useUserStore} from '@/store/modules/user';
import {countSnCode} from '@/api/function/sealno/sealno';
import {getSignature} from '@/api/function/common/wechat';
import {getUserInfo} from '@/api/function/user/user';
import {findMyToDoNumber} from '@/api/function/sealnoFlow/sealnoFlow';

const showCustomToast = ref(false);
const toastMessage = ref('');

const showToast = (message: string) => {
  toastMessage.value = message;
  showCustomToast.value = true;
  setTimeout(() => showCustomToast.value = false, 1500);
};

onMounted(async () => {
  // 获取用户信息
  try {
    const userRes = await getUserInfo();
    console.log('获取用户信息:', userRes);
    nickName.value = userRes.data.nickname;
    deptName.value = userRes.data.deptName;
    if (userRes.data.user?.avatar) {
      const backendUrl = process.env.NODE_ENV === 'production' ?
          window.location.origin+"/seano" : 'http://127.0.0.1:17080/seano';
      // 修改拼接逻辑，直接拼接 avatar 路径
      avatarUrl.value = `${backendUrl}${userRes.data.user.avatar}`;
      console.log('拼接后的头像 URL:', avatarUrl.value); // 打印拼接后的头像 URL
    } else {
      // 如果 avatar 为空，设置默认头像
      avatarUrl.value = '/static/images/default-avatar.png';
    }
  } catch (error) {
    console.error('获取用户信息失败:', error);
    // 如果请求失败，设置默认头像
    avatarUrl.value = '/static/images/default-avatar.png';
  }
  // 初始化时获取待办数量
  await fetchTodoCount();
  // 配置 wx.config
  await configureWx();
})
const configureWx = async () => {
  try {
    // 获取 accessToken
    // const accessTokenResponse = await getAccessToken();
    // const accessToken = accessTokenResponse.data;
    //
    // 获取 jsapiTicket
    // const jsapiTicketResponse = await getJsapiTicket(accessToken);
    // const jsapiTicket = jsapiTicketResponse.data;

    const currentUrl = window.location.href.split('#')[0];
    const signatureData = await getSignature(currentUrl);
    console.log('getSignature 返回值:', signatureData);

    // 直接配置 wx.config，因为微信 JS SDK 已经在 main.js 中加载
    jWeixin.config({
      beta: true,
      debug: false,
      appId: 'wl6e538311bc',
      timestamp: signatureData.data.timestamp,
      nonceStr: signatureData.data.nonceStr,
      signature: signatureData.data.signature,
      jsApiList: ['scanQRCode','checkJsApi']
    });
  } catch (error) {
    console.error('配置 wx.config 失败:', error);
    throw error;
  }
};

// 获取用户昵称和部门名称
const userStore = useUserStore();
const nickName = ref();
const deptName = ref();
const avatarUrl = ref(userStore.getterAvatar);

// 控制操作弹窗是否显示
const isPopupVisible = ref(false);
// 当前扫描的铅封编号
const currentSnCode = ref('');

// 新增的状态变量
const isScanPopupVisible = ref(false);
const isManualInputVisible = ref(false);
const isTracePopupVisible = ref(false);

// 新增一个标记来区分是从哪里进入的手动输入
const isFromTrace = ref(false);

// 功能列表数据
const functionList = ref([
  {name: '库存管理', icon: 'shop', type: 'storage'},
  {name: '配送计划', icon: 'list', type: 'delivery'},
  {name: '铅封溯源', icon: 'paperclip', type: 'trace'},
  {
    name: '我的待办',
    image: '/static/images/function/pages/myToDo/todo.png',
    type: 'myToDo',
    badge: '0', // 初始值设为0
    badgeColor: '' // 初始化颜色为空
  },
  {name: '我的已办', image: '/static/images/function/pages/myDone/completed.png', type: 'myDone'},
  {name: '我的申报', image: '/static/images/function/pages/myLaunch/apply.png', type: 'myLaunch'},
  {name: '小额配送', icon: 'settings', type: 'customSend'},
  {name: '车辆维修', image: '/static/images/function/pages/truckRepair/car.png', type: 'truckRepair'}
]);

// 获取待办数量并更新badge
const fetchTodoCount = async () => {
  try {
    const response = await findMyToDoNumber(); // 调用接口
    const todoCount = response.data || 0; // 确保数值安全
    const todoItem = functionList.value.find(item => item.type === 'myToDo');

    if (todoItem) {
      todoItem.badge = todoCount.toString();
      todoItem.badgeColor = getBadgeColor(todoCount); // 计算颜色
    }
  } catch (error) {
    console.error('获取待办数量失败:', error);
    showToast('待办数量加载失败');
  }
};

// 新增：根据待办数量计算颜色
const getBadgeColor = (count: number): string => {
  if (count <= 0) return 'transparent'; // 隐藏badge
  if (count <= 9) return '#FFD700'; // 黄色
  if (count <= 30) return '#FF8C00'; // 橙黄色
  return '#FF4D4F'; // 红色
};

// 修改原有的handleScanClick方法
const handleScanClick = () => {
  isScanPopupVisible.value = true;
};

// 新增的方法
const closeScanPopup = () => {
  isScanPopupVisible.value = false;
};

const showManualInput = () => {
  isScanPopupVisible.value = false;
  isManualInputVisible.value = true;
  isFromTrace.value = false;
};

const closeManualInput = () => {
  isManualInputVisible.value = false;
  isFromTrace.value = false;
};

const handleScan = async () => {
  console.log("执行扫码操作");

  try {
	  jWeixin.scanQRCode({
      desc: '固态施拆扫码触发',
      needResult: 1,
      scanType: ["qrCode", "barCode"],
      success: async (res) => {
        // currentSnCode.value = JSON.stringify(res);
        currentSnCode.value = res.resultStr;
        await validateSnCode(currentSnCode.value, isFromTrace.value);
        if (!isFromTrace.value) {
          uni.hideKeyboard();
          try {
            const result = await countSnCode(currentSnCode.value);
            if (result.code === 200 && result.data > 0) {
              isManualInputVisible.value = false;
              if (isFromTrace.value) {
                // 如果是从铅封溯源进入，直接跳转到溯源页面
                uni.navigateTo({
                  url: `/pages/function/sealnoUnseal/index?snCode=${currentSnCode.value}`
                });
              } else {
                // 如果是从主页面扫码进入，显示拆封和施打选项
                isPopupVisible.value = true;
              }
            } else {
              showToast('铅封编号无效');
              return;
            }
          } catch (error) {
            showToast('网络请求失败');
          }
        }
        isPopupVisible.value = true; // 显示操作弹窗
      }
	  });
  } catch (error) {
    console.error('扫码操作失败:', error);
    uni.showToast({ title: '扫码功能初始化失败', icon: 'none' });
  }
};

const handleConfirmInput = async () => {
  if (!currentSnCode.value) {
    showToast('请输入铅封编号');
  }

  await validateSnCode(currentSnCode.value, isFromTrace.value);
  uni.hideKeyboard();
  try {
    const result = await countSnCode(currentSnCode.value);
    if (result.code === 200 && result.data > 0) {
      isManualInputVisible.value = false;
      if (isFromTrace.value) {
        // 如果是从铅封溯源进入，直接跳转到溯源页面
        uni.navigateTo({
          url: `/pages/function/sealnoOperate/index?snCode=${currentSnCode.value}`
        });
      } else {
        // 如果是从主页面扫码进入，显示拆封和施打选项
        isPopupVisible.value = true;
      }
    } else {
      showToast('铅封编号无效');
      return;
    }
  } catch (error) {
    showToast('网络请求失败');
  }
};

// 处理功能区域点击事件
const handleFunction = async (type: string) => {
  if (type === 'storage') {
    uni.navigateTo({
      url: '/pages/function/sealnoStock/index'
    });
    return;
  }
  if (type === 'delivery') {
    uni.navigateTo({
      url: '/pages/function/truckBill/index'
    });
    return;
  }
  if (type === 'trace') {
    isTracePopupVisible.value = true;
    return;
  }
  if (type === 'myLaunch') {
    uni.navigateTo({
      url: '/pages/function/myLaunch/index'
    });
    return;
  }
  if (type === 'myToDo') {
    uni.switchTab({
      url: '/pages/function/myToDo/index'
    });
    return;
  }
  if (type === 'myDone') {
    uni.navigateTo({
      url: '/pages/function/myDone/index'
    });
    return;
  }
  if (type === 'customSend') {
    uni.navigateTo({
      url: '/pages/function/customSend/index'
    });
    return;
  }
  if (type === 'truckRepair') {
    uni.navigateTo({
      url: '/pages/function/truckRepair/index'
    });
    return;
  }
  console.log('功能点击：', type);
};

// 处理拆封操作
const onUnseal = () => {
  closePopup();
  uni.navigateTo({
    url: `/pages/function/sealnoUnseal/index?snCode=${currentSnCode.value}&businessType=FIXED_WORK&billNo=`
  });
};

// 处理施打操作
const onApply = () => {
  closePopup();
  uni.navigateTo({
    url: `/pages/function/sealnoApply/index?snCode=${currentSnCode.value}&businessType=FIXED_WORK&billNo=`
  });
};

// 关闭操作弹窗
const closePopup = () => {
  isPopupVisible.value = false;
};

const closeTracePopup = () => {
  isTracePopupVisible.value = false;
};

const handleTraceScan = async () => {
  console.log("handleTraceScan");
  isTracePopupVisible.value = false; // 关闭弹窗
  try {
    isFromTrace.value = true;
    await handleScan();
  } catch (error) {
    console.error("扫码失败:", error);
    showToast('扫码失败');
  }
};

const validateSnCode = async (snCode: string, isTrace: boolean) => {
  console.log("进入方法", snCode);
  try {
    const result = await countSnCode(snCode);
    if (result.code === 200 && result.data > 0) {
      currentSnCode.value = snCode; // 保存编号
      if (isTrace) { // 溯源场景直接跳转
        uni.navigateTo({url: `/pages/function/sealnoOperate/index?snCode=${snCode}`});
      } else { // 主场景显示操作弹窗
        isPopupVisible.value = true;
      }
    } else {
      showToast('铅封编号无效');
      return;
    }
  } catch (error) {
    showToast('网络请求失败');
  }
};

const showTraceManualInput = () => {
  closeTracePopup();
  isManualInputVisible.value = true;
  isFromTrace.value = true;
};
</script>

<style>
/* 页面整体高度 */
page {
  height: 100%;
  padding-bottom: 100px;
  background-color: #fff;
}

/* 容器样式 */
.container {
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: #fff;
  padding-top: 80rpx;
  padding-bottom: 100px;
}

/* 顶部个人信息区域 */
.header {
  padding: 32rpx;
  display: flex;
  align-items: center;
  margin-bottom: 32rpx;
}

.avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 40rpx;
  background-color: #f0f0f0;
  display: flex;
  align-items: center;
  justify-content: center;
}

.user-info {
  margin-left: 24rpx;
  flex: 1;
}

.name {
  font-size: 16px;
  color: #333;
  font-weight: 500;
  display: block;
}

.position {
  font-size: 12px;
  color: #666;
  margin-top: 8rpx;
  display: block;
  max-width: 480rpx;
}

/* 扫码区域 */
.scan-area {
  padding: 120rpx 0;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.scan-button {
  width: 300rpx;
  height: 300rpx;
  border-radius: 150rpx;
  background-color: #000;
  display: flex;
  align-items: center;
  justify-content: center;
}

.scan-text {
  font-size: 14px;
  color: #666;
  margin-top: 20rpx;
}

/* 功能区域 */
.function-grid {
  padding: 32rpx;
  margin-top: 48rpx;
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 32rpx;
}

.grid-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.icon-wrapper {
  position: relative;
  width: 48px;
  height: 48px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.badge {
  position: absolute;
  top: -4px;
  right: -4px;
  background-color: #ff4d4f;
  color: #fff;
  font-size: 12px;
  padding: 0 6px;
  border-radius: 8px;
  min-width: 16px;
  height: 16px;
  line-height: 16px;
  text-align: center;
}

.function-text {
  font-size: 14px;
  color: #333;
  margin-top: 12rpx;
}

/* 操作弹窗样式 */
/* 遮罩层样式 */
.popup-mask {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1001;
}

/* 弹窗内容样式 */
.popup-content {
  background-color: #fff;
  padding: 20px 0;
  border-radius: 15px;
  width: 80%;
  max-width: 350px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
}

/* 弹窗头部样式 */
.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  padding: 0;
  position: relative;
}

/* 弹窗标题样式 */
.popup-title {
  font-size: 18px;
  font-weight: bold;
  margin-left: 32rpx;
  text-align: left;
}

.operation-title {
  margin-left: 32rpx;
  text-align: left;
}

.popup-buttons {
  padding: 32rpx;
  display: flex;
  justify-content: space-between;
  margin-top: 40rpx;
  gap: 20rpx;
}

.action-button {
  height: 112rpx;
  width: 300rpx; /* 增加宽度 */
  margin: 0 0 24rpx 0;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 32rpx;
  border-radius: 16rpx;
  transition: transform 0.2s ease;
}

.action-button:active {
  transform: scale(0.98);
}

.action-button:last-child {
  margin-bottom: 0;
}

.outlined {
  background-color: #ffffff;
  border: 2rpx solid #2979ff;
  color: #2979ff;
}

/* 新增的样式 */
.scan-popup {
  padding-bottom: 32rpx;
}

.scan-options {
  display: flex;
  justify-content: space-around;
  align-items: center;
  padding: 48rpx 32rpx;
}

.scan-option {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16rpx;
}

.scan-icon-wrapper {
  width: 120rpx;
  height: 120rpx;
  background-color: #f0f7ff;
  border-radius: 60rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  transition: background-color 0.2s ease;
}

.scan-icon-wrapper:active {
  background-color: #e6f0ff;
}

.scan-divider {
  width: 2rpx;
  height: 120rpx;
  background-color: #f0f0f0;
  margin: 0 32rpx;
}

.manual-input {
  width: 100%;
  height: 88rpx;
  background-color: #f5f5f5;
  border-radius: 12rpx;
  padding: 0 24rpx;
  font-size: 28rpx;
  margin-bottom: 32rpx;
  text-align: left;
}

.input-placeholder {
  color: #999999;
  text-align: left !important;
  padding-left: 0;
}

.confirm-button {
  width: 100%;
  height: 88rpx;
  border-radius: 12rpx;
  background: linear-gradient(to right, #2979ff, #3f8cff);
  box-shadow: 0 4rpx 12rpx rgba(41, 121, 255, 0.2);
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
  border: none;
}

.confirm-button:active {
  transform: scale(0.98);
  box-shadow: 0 2rpx 6rpx rgba(41, 121, 255, 0.1);
}

.button-text {
  color: #ffffff;
  font-size: 32rpx;
  font-weight: 500;
  letter-spacing: 2rpx;
}

.popup-close {
  position: absolute;
  right: 24rpx;
  top: 50%;
  transform: translateY(-50%);
  width: 48rpx;
  height: 48rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

@keyframes fadeIn {
  from { opacity: 0; }
  to { opacity: 1; }
}

@keyframes scaleIn {
  from {
    transform: scale(0.8);
    opacity: 0;
  }
  to {
    transform: scale(1);
    opacity: 1;
  }
}

/* 添加自定义输入框样式 */
.modal-input {
  text-align: left;
  padding-left: 10px;
}

.uni-modal-input {
  padding-left: 10px !important;
}

.uni-modal-input-placeholder {
  text-align: left !important;
}

.manual-input-popup .input-area {
  padding: 32rpx;
}

/* 修改弹窗头部样式 */
.manual-input-popup .popup-header {
  padding: 0 32rpx;
  margin-bottom: 0;
}

.manual-input-popup .popup-title {
  font-size: 18px;
  font-weight: bold;
  text-align: left;
}

.icon-img {
  width: 28px;
  height: 28px;
  object-fit: contain;
}

.custom-toast {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  padding: 16rpx 32rpx;
  background-color: rgba(0, 0, 0, 0.8);
  color: #ffffff;
  border-radius: 8rpx;
  font-size: 14px;
  min-width: 150rpx;
  text-align: center;
  z-index: 999999;
}

.bottom-placeholder {
  min-height: 50px;
}

.badge {
  /* 其他样式不变 */
  position: absolute;
  top: -4px;
  right: -4px;
  color: #fff;
  font-size: 12px;
  padding: 0 6px;
  border-radius: 8px;
  min-width: 16px;
  height: 16px;
  line-height: 16px;
  text-align: center;

  /* 新增：动态背景色（通过CSS变量实现） */
  background-color: v-bind('badgeColor'); /* 关键：绑定JS中的badgeColor属性 */
}

/* 测试按钮样式（保持原有样式） */
.test-button {
  position: fixed;
  bottom: 50px;
  right: 30px;
  padding: 16rpx 32rpx;
  background-color: #2979ff;
  color: #fff;
  border-radius: 24rpx;
  font-size: 16px;
  z-index: 1002;
  box-shadow: 0 2rpx 8rpx rgba(41, 121, 255, 0.2);
}
</style>
